﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P4210Controller : ControllerBase
    {



        /// <summary>
        /// NA 单增加
        /// </summary>
        /// <param name="P4210param">用户名</param>
        /// <param name="password">密码</param>
        /// <param name="ordernumber">订单号</param>
        /// <param name="itemtype">开单产品类型 normal 正常品     danger 危险品</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> Create(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            Dictionary<int, string> detailinfos = new Dictionary<int, string>();
            int index = 0;
            //string username = objpram["username"].ToString();
            //string password = objpram["password"].ToString();
            //string ordernumber = objpram["ordernumber"].ToString();

            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objpram).ToString());


            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()} 新增NA单据 {param.ordernumber}  { param.itemtype}");

                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();
                foreach (DataRow dr in new BLL.orderHandler().GetOrder(param.ordernumber)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "35", value = dr["BU"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "608", value = dr["OrderNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "663", value = dr["Remark"].ToString(), command = "SetGridCellValue" });
                    if (!string.IsNullOrWhiteSpace(dr["Region"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "1065", value = dr["Region"].ToString(), command = "SetGridCellValue" });

                    if (string.IsNullOrWhiteSpace(param.itemtype))
                    {
                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                        Console.WriteLine($"{DateTime.Now.ToString()}  { dr["ItemNumber"]} {dr["Remark"]} {dr["ItemType"]}");
                    }
                    else
                    {
                        if (param.itemtype.Equals("normal"))
                        {
                            if (!dr["ItemType"].ToString().Contains("危险品"))
                            {
                                gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                                Console.WriteLine($"{DateTime.Now.ToString()}  { dr["ItemNumber"]} {dr["Remark"]} {dr["ItemType"]}");
                            }
                        }
                        else if (param.itemtype.Equals("danger"))
                        {
                            if (dr["ItemType"].ToString().Contains("危险品"))
                            {
                                gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                                Console.WriteLine($"{DateTime.Now.ToString()}  { dr["ItemNumber"]} {dr["Remark"]} {dr["ItemType"]}");
                            }
                        }
                    }

                   


                    detailinfos.Add(index, SetErrLineMsg(index.ToString(), dr["ItemNumber"].ToString(), dr["Quantity"].ToString(), dr["Region"].ToString()));
                    index++;
                    lastrow = dr;
                }


                if (lastrow.Table.Rows.Count<=0)
                    throw new MQException("401", $"订单{param.ordernumber} 没有可以生成的数据！");


                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        //new FSREvent() { controlID="11", command="SetControlValue", value= lastrow["BU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="800", command="SetControlValue",value=lastrow["AddressNumber"].ToString()   },
                                        new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P58E4210_W58E4210A",
                    version = "MBR001A",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                System.Threading.Thread.Sleep(15000);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NAno = obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_28"]["value"].ToString();
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NA单:{NAno}");
                    Log4Net.Debug($"{param.ordernumber}生成NA单:{NAno}");
                    execresult.Result = NAno;
                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"{param.ordernumber}请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
                //2023-10-16 增加当可供量不足的时候，提示是哪一行
                int errline = CommonHandler.GetErrorControlLine(x.Message);
                if (errline >= 0)
                    execresult.Message += System.Environment.NewLine + detailinfos[errline];

                Console.WriteLine($"{DateTime.Now.ToString()}  请求返回异常:{execresult.Message}");
                execresult.Result = x.Message;
            }
            return execresult;
        }

        /// <summary>
        /// 从拣货单产生NA单，指定批号、货位，用于虚拟调拨流程
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreateNAFromPick(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            string ordernumber = objpram["ordernumber"].ToString();
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(username, password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增NA单据(拣货单数据){ordernumber}");
                Log4Net.Error($" 新增NA单据(拣货单数据){ordernumber}");
                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();
                foreach (DataRow dr in new BLL.orderHandler().GetOrderFrompickinggoods(ordernumber)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "35", value = dr["BU"].ToString(), command = "SetGridCellValue" });
                    //col.Add(new gridcolumnevent() { columnID = "1065", value = dr["fromInvregion"].ToString(), command = "SetGridCellValue" });


                    col.Add(new gridcolumnevent() { columnID = "608", value = dr["OrderNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "132", value = dr["Tolocation"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "133", value = dr["lotn"].ToString(), command = "SetGridCellValue" });
                    if (!string.IsNullOrWhiteSpace(dr["ToInvregion"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "1065", value = dr["ToInvregion"].ToString(), command = "SetGridCellValue" });


                    //// 2024-12-05 增加为了经销商虚拟调拨，生成的时候带价格和备注系信息
                    ///  不对，因为JDE录入价格的界面是另外一个版本，所以此处设置了价格也不会生效，
                    ////填入单价
                    //if (Convert.ToDecimal(dr["Price"].ToString()) > 0)
                    //{
                    //    col.Add(new gridcolumnevent() { columnID = "57", value = dr["Price"].ToString(), command = "SetGridCellValue" });
                    //}
                    if (!string.IsNullOrWhiteSpace(dr["Remark"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "663", value = dr["Remark"].ToString(), command = "SetGridCellValue" });



                    gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        //new FSREvent() { controlID="11", command="SetControlValue", value= lastrow["BU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="800", command="SetControlValue",value=lastrow["AddressNumber"].ToString()   },
                                        new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P58E4210_W58E4210A",
                    version = "MBR001A",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                System.Threading.Thread.Sleep(10000);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NAno = obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_28"]["value"].ToString();
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NA单:{NAno}");
                    Log4Net.Error($" 新增NA单据(拣货单数据){ordernumber} 生成NA单:{NAno}");

                    execresult.Result = NAno;
                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
                execresult.Result = x.Message;
            }
            return execresult;
        }


        /// <summary>
        /// 从拣货单产生NA单，指定批号、货位，用于虚拟调拨流程\
        ///  增加可以带入单价
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreateNAWithPrice(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            //string username = objpram["username"].ToString();
            //string password = objpram["password"].ToString();
            //string ordernumber = objpram["ordernumber"].ToString();
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objpram).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增NA单据带价格 {param.ordernumber}");

                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();
                foreach (DataRow dr in new BLL.orderHandler().GetOrderFrompickinggoods(param.ordernumber)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "35", value = dr["BU"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "608", value = dr["OrderNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });

                    //

                    if(!string.IsNullOrWhiteSpace(dr["Tolocation"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "132", value = dr["Tolocation"].ToString(), command = "SetGridCellValue" });

                    if (!string.IsNullOrWhiteSpace(dr["lotn"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "133", value = dr["lotn"].ToString(), command = "SetGridCellValue" });


                    if (!string.IsNullOrWhiteSpace(dr["ToInvregion"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "1065", value = dr["ToInvregion"].ToString(), command = "SetGridCellValue" });

                    //填入单价
                    if (Convert.ToDecimal(dr["Price"].ToString()) > 0)
                    {
                        col.Add(new gridcolumnevent() { columnID = "57", value = dr["Price"].ToString(), command = "SetGridCellValue" });
                    }
                    if (!string.IsNullOrWhiteSpace(dr["Remark"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "663", value = dr["Remark"].ToString(), command = "SetGridCellValue" });

                    //2024-11-12  加入产品类型进行开单
                    if (string.IsNullOrWhiteSpace(param.itemtype))
                    {
                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                        Console.WriteLine($"{DateTime.Now.ToString()}  { dr["ItemNumber"]} {dr["Remark"]} {dr["ItemType"]}");
                    }
                    else
                    {
                        if (param.itemtype.Equals("normal"))
                        {
                            if (!dr["ItemType"].ToString().Contains("危险品"))
                            {
                                gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                                Console.WriteLine($"{DateTime.Now.ToString()}  { dr["ItemNumber"]} {dr["Remark"]} {dr["ItemType"]}");
                            }
                        }
                        else if (param.itemtype.Equals("danger"))
                        {
                            if (dr["ItemType"].ToString().Contains("危险品"))
                            {
                                gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                                Console.WriteLine($"{DateTime.Now.ToString()}  { dr["ItemNumber"]} {dr["Remark"]} {dr["ItemType"]}");
                            }
                        }
                    }
                    //gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                    //Console.WriteLine($"{DateTime.Now.ToString()}  { dr["ItemNumber"]}  { dr["Quantity"]}  { dr["Price"]} ");
                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        //new FSREvent() { controlID="11", command="SetControlValue", value= lastrow["BU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="800", command="SetControlValue",value=lastrow["AddressNumber"].ToString()   },
                                        new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P58E4210_W58E4210A",
                    version = "MBR002S",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                System.Threading.Thread.Sleep(6000);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NAno = obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_28"]["value"].ToString();
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NA单:{NAno}");
                    Log4Net.Debug($"{param.ordernumber}生成NA单:{NAno}");
                    execresult.Result = NAno;
                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
                execresult.Result = x.Message;
            }
            return execresult;
        }


        [HttpPost]
        public ActionResult<MQResponse> CreateNW(dynamic objparam)
        {
            Console.WriteLine(objparam);
            Dictionary<int, string> detailinfos = new Dictionary<int, string>();
            int index = 0;
            //用了新的方式，哈哈方便多了
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增NW单据 {param.orderid}");
                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();

                foreach (DataRow dr in new BLL.orderHandler().GetNWOrder(param.orderid)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "1065", value = dr["fromInvregion"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "608", value = dr["ToInvregion"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "132", value = dr["location"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "133", value = dr["lotn"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "663", value = dr["LOB"].ToString(), command = "SetGridCellValue" });

                    if ("/PRI/SRI/".IndexOf("/" + dr["Tolocation"].ToString().ToUpper() + "/") < 0)
                    {   
                        col.Add(new gridcolumnevent() { columnID = "456", value = dr["Tolocation"].ToString(), command = "SetGridCellValue" });
                    }
                    if (!string.IsNullOrWhiteSpace(dr["ShipToCode"].ToString()))
                    {
                        col.Add(new gridcolumnevent() { columnID = "164", value = dr["ShipToCode"].ToString(), command = "SetGridCellValue" });
                        Console.WriteLine($"调拨成都的单据需要更改地址");
                    }

                    gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                    detailinfos.Add(index, SetErrLineMsg(index.ToString(), dr["ItemNumber"].ToString(), dr["Quantity"].ToString(), dr["fromInvregion"].ToString()));
                    index++;

                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        new FSREvent() { controlID="716", command="SetControlValue", value= lastrow["FromBU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="718", command="SetControlValue",value=lastrow["ToBU"].ToString()   },
                                        //new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        //new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        //new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P58E4210_W58E4210A",
                    version = "MBR001W",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                //System.Threading.Thread.Sleep(3000);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NWno = $"NW{obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_757"]["value"].ToString()}";
                    NWno += $"#{ obj["fs_P58E4210_W58E4210A"]["data"]["z_DCTO_774"]["value"].ToString()}{ obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_776"]["value"].ToString()}";
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NW单:{NWno}");
                    execresult.Result = NWno;
                    execresult.Message = response.JsonString;
                }
            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
                int errline = CommonHandler.GetErrorControlLine(x.Message);
                if (errline >= 0)
                    execresult.Message += System.Environment.NewLine + detailinfos[errline];

                Console.WriteLine($"{DateTime.Now.ToString()}  请求返回异常:{x.Message}");

                execresult.Result = x.Message;
            }
            return execresult;


        }

        /// <summary>
        /// 新增近效期NW单
        /// </summary>
        /// <param name="objparam"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreateNWNOinvregion(dynamic objparam)
        {
            Console.WriteLine(objparam);
            //用了新的方式，哈哈方便多了
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增近效期NW单据");
                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();

                foreach (DataRow dr in new BLL.orderHandler().GetNWOrder(param.orderid)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    //col.Add(new gridcolumnevent() { columnID = "1065", value = dr["fromInvregion"].ToString(), command = "SetGridCellValue" });
                    //col.Add(new gridcolumnevent() { columnID = "608", value = dr["ToInvregion"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "132", value = dr["location"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "133", value = dr["lotn"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "663", value = dr["LOB"].ToString(), command = "SetGridCellValue" });

                    //if ("/PRI/SRI/".IndexOf("/" + dr["Tolocation"].ToString().ToUpper() + "/") < 0)
                    //{
                    //    // 卸岸成本
                    //    col.Add(new gridcolumnevent() { columnID = "456", value = dr["Tolocation"].ToString(), command = "SetGridCellValue" });
                    //}

                    if (!string.IsNullOrWhiteSpace(dr["ShipToCode"].ToString()))
                    {
                        col.Add(new gridcolumnevent() { columnID = "164", value = dr["ShipToCode"].ToString(), command = "SetGridCellValue" });
                        Console.WriteLine($"调拨成都的单据需要更改地址");
                    }


                    gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        new FSREvent() { controlID="716", command="SetControlValue", value= lastrow["FromBU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="718", command="SetControlValue",value=lastrow["ToBU"].ToString()   },
                                        //new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        //new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        //new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P4210_W4210A",
                    version = "MBR001W",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                System.Threading.Thread.Sleep(1000);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210A"))
                {
                    JObject obj = response.ToJObject();
                    Log4Net.Debug($"{response.JsonString}");
                    //应该查询到数据
                    string NWno = $"NW{obj["fs_P4210_W4210A"]["data"]["z_DOCO_757"]["value"].ToString()}";
                    NWno += $"#{ obj["fs_P4210_W4210A"]["data"]["z_DCTO_774"]["value"].ToString()}{ obj["fs_P4210_W4210A"]["data"]["z_DOCO_776"]["value"].ToString()}";
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成近效期NW单:{NWno}");
                    Log4Net.Debug($" 生成近效期NW单:{NWno}");
                    execresult.Result = NWno;
                }
            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
            }
            return execresult;


        }
        /// <summary>
        ///  修改NA单的货位为SRI
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> UpdateLocation(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            string username = objpram["username"].ToString();
            string password = objpram["password"].ToString();
            string ordernumber = objpram["ordernumber"].ToString();
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;
            try
            {
                if (string.IsNullOrWhiteSpace(username) || string.IsNullOrWhiteSpace(password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                //try
                //{
                //    OAuthController oAuth = new OAuthController();
                //    oAuth.GetToken(objpram);
                //}
                //catch (Exception x)
                //{
                //    throw new MQException("401", x.Message);
                //}
                //if (string.IsNullOrWhiteSpace(SomeHandler.GetToken(username)))
                //{
                //    throw new Exception("验证失败，请检查用户名密码是否正确！");
                //}
                //token = SomeHandler.GetToken(username);

                token = SomeHandler.GetToken(username, password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{username} Token:{token}");

                Console.WriteLine($"{DateTime.Now.ToString()} 查找NA单据 {ordernumber}");
                #region 处理代码
                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    returnControlIDs = "1[45,46]",
                    formName = "P58E4210_W58E4210E",
                    version = "MBR001A",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                   ,
                    formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                      new FSREvent() { controlID="1[45]", command="SetQBEValue" ,value=ordernumber },
                                      new FSREvent() { controlID="28", command="DoAction"  }
                                     }
                                 )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P58E4203_W58E4203A",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest
                    
                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210E"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt16(obj["fs_P58E4210_W58E4210E"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"查询到{rowcount-1}条记录");
                    

                    if (rowcount > 1)
                    {
                        Console.WriteLine("选择第一条记录，并打开编辑界面");
                        ActionRequest actionRequest = new ActionRequest()
                        {
                            returnControlIDs = "1[53,89,35,132,133,34,664]",
                            formOID = "W58E4210E",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                      new FSREvent() { controlID="1.0", command="SelectRow"   },
                                      new FSREvent() { controlID="4", command="DoAction"  }
                                      }
                                  )
                             ,stopOnWarning="false"
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                        {
                            ///获取结果的总行数
                            obj = response.ToJObject();
                            rowcount = Convert.ToInt32(obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["summary"]["records"]);
                            List<gridrowupdateevents> gridrows = new List<gridrowupdateevents>();
                            List<gridcolumnevent> gridcols = new List<gridcolumnevent>();
                            gridcols.Add(new gridcolumnevent()
                            {
                                columnID = "132",
                                command = "SetGridCellValue",
                                value = "SRI"
                            }
                           
                            );
                            //gridcols.Add(new gridcolumnevent()
                            //    {
                            //        columnID = "664",
                            //        command = "SetGridCellValue",
                            //        value = "PRI"
                            //    }
                            //);
                            for (int i = 0; i < rowcount; i++)
                            {
                                Console.WriteLine($"正在处理第{i}行  原货位{obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["rowset"][i]["z_LOCN_132"]["value"].ToString()}");
                                stackId = response.stackId;
                                stateId = response.stateId;
                                int rowindex = Convert.ToInt32(obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["rowset"][i]["rowIndex"]);
                                //[JSON].fs_P58E4210_W58E4210A.data.gridData.rowset.[0].z_LOCN_132.value
                                //[JSON].fs_P58E4210_W58E4210A.data.gridData.rowset.[0].z_LOCN_132.value
                                //if (obj["fs_P58E4210_W58E4210A"]["data"]["gridData"]["rowset"][i]["z_LOCN_132"]["value"].ToString().Contains( "PRI"))
                                //{
                                 
                                    gridrows.Add(new gridrowupdateevents()
                                    {
                                        gridColumnEvents = gridcols,
                                        rowNumber = rowindex
                                    });
                                //}

                            }


                            actionRequest = new ActionRequest()
                            {
                                //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W58E4210A",
                                formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {
                                      new FSREvent() { controlID="1.0", command="SelectRow" ,gridAction =new GridAction(){
                                          gridID="1",gridRowUpdateEvents=gridrows
                                      } },
                                      new FSREvent() { controlID="4", command="DoAction"  }
                                         }
                                     )
                                 ,stopOnWarning="false"
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                allowCache = true,
                                action = "execute",
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };

                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            needclose = true;
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                            //Console.WriteLine(response.JsonString);
                            Console.WriteLine($"{DateTime.Now.ToString()} {ordernumber}修改完成:{response.currentApp}");
                            if (response.currentApp.Contains("P58E4210_W58E4210A"))
                            {// 修改不成功，会停留在当前页面
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210A"))
                                {
                                    //不用做点什么
                                }
                            }
                            else
                            {
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P58E4210_W58E4210E"))
                                {
                                    obj = response.ToJObject();
                                    //应该查询到数据
                                    //string NAno = obj["fs_P58E4210_W58E4210E"]["data"]["gridData"]["rowset"]["0"]["z_DOCO_45"].ToString();
                                    execresult.Result = ordernumber;
                                    execresult.Message = response.JsonString;
                                }
                            }



                        }

                    }
                    else
                    {
                        throw new MQException("404",$"找不到单据{ordernumber},请联系管理员！");
                    }
                }
                #endregion
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W58E4210A"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    //Console.WriteLine(response.JsonString);
                }
                #endregion
            }
            return execresult;
        }




        /// <summary>
        /// NT 单增加
        /// </summary>
        /// <param name="objparam"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreateNT(dynamic objparam)
        {
            Log4Net.Debug(objparam);
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>(((Newtonsoft.Json.Linq.JObject)objparam).ToString());


            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  新增NT 单据 {param.orderid}");

                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();

                DataTable dt = new BLL.orderHandler().GetNTOrder(param.orderid)[0];

                foreach (DataRow dr in dt.Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "35", value = dr["BU"].ToString(), command = "SetGridCellValue" });


                    //col.Add(new gridcolumnevent() { columnID = "608", value = dr["OrderNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });
                    //col.Add(new gridcolumnevent() { columnID = "132", value = "PRI", command = "SetGridCellValue" });
                    if (!string.IsNullOrWhiteSpace(dr["LOCN"].ToString()))
                        col.Add(new gridcolumnevent() { columnID = "132", value = dr["LOCN"].ToString(), command = "SetGridCellValue" });

                    gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        //new FSREvent() { controlID="11", command="SetControlValue", value= lastrow["BU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="800", command="SetControlValue",value=lastrow["AddressNumber"].ToString()   },
                                        new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() }
                                        //new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P4210_W4210A",
                    version = "MCL401",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "100",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                System.Threading.Thread.Sleep(3000);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NTno = obj["fs_P4210_W4210A"]["data"]["z_DOCO_28"]["value"].ToString();
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NT单:{NTno}");
                    execresult.Result = NTno;
                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
            }
            return execresult;
        }


        [HttpPost]
        public ActionResult<MQResponse> CreateNR(dynamic objparam)
        {
            Console.WriteLine(objparam);
            Dictionary<int, string> detailinfos = new Dictionary<int, string>();
            int index = 0;
            //用了新的方式，哈哈方便多了
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new MQException("120","请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  按申请数量 新增NR单据 {param.orderid}");
                Log4Net.Error($"按申请数量 新增NR单据 {param.orderid}");
                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();

                foreach (DataRow dr in new BLL.orderHandler().GetNROrder(param.orderid)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString().Trim(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "1065", value = dr["fromInvregion"].ToString().Trim(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "608", value = dr["ToInvregion"].ToString().Trim(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = dr["Quantity"].ToString(), command = "SetGridCellValue" });
                    //col.Add(new gridcolumnevent() { columnID = "132", value = dr["location"].ToString(), command = "SetGridCellValue" });
                    //col.Add(new gridcolumnevent() { columnID = "133", value = dr["lotn"].ToString(), command = "SetGridCellValue" });
                    //col.Add(new gridcolumnevent() { columnID = "663", value = dr["LOB"].ToString(), command = "SetGridCellValue" });

                    //if ("/PRI/SRI/".IndexOf("/" + dr["Tolocation"].ToString().ToUpper() + "/") < 0)
                    //{
                    //    col.Add(new gridcolumnevent() { columnID = "456", value = dr["Tolocation"].ToString(), command = "SetGridCellValue" });
                    //}
                    if (!string.IsNullOrWhiteSpace(dr["ShipToCode"].ToString()))
                    {
                        col.Add(new gridcolumnevent() { columnID = "164", value = dr["ShipToCode"].ToString().Trim(), command = "SetGridCellValue" });
                    }
                    //2024-06-27 IT 要求增加配额到664  最终用途中
                    //TMD配额里面有空格造成他娘的JDE生成失败，还报价格为0，误导用户
                    if (!string.IsNullOrWhiteSpace(dr["ToQuota"].ToString()))
                    {
                        col.Add(new gridcolumnevent() { columnID = "664", value = dr["ToQuota"].ToString().Trim(), command = "SetGridCellValue" });
                    }

                    if (Convert.ToInt32(dr["Quantity"].ToString()) != 0)
                    {
                        Console.WriteLine($"{DateTime.Now.ToString()}  {dr["ItemNumber"]},{dr["Quantity"]}, {dr["fromInvregion"]}  配额:{dr["ToQuota"]}");
                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                        detailinfos.Add(index, SetErrLineMsg(index.ToString(), dr["ItemNumber"].ToString(), dr["Quantity"].ToString(), dr["fromInvregion"].ToString()));
                        index++;
                    }
                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        new FSREvent() { controlID="716", command="SetControlValue", value= lastrow["FromBU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="718", command="SetControlValue",value=lastrow["ToBU"].ToString()   },
                                        //new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        //new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        //new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P58E4210_W58E4210A",
                    version = "MBR001",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                //System.Threading.Thread.Sleep(3000);
                if (CommonHandler.ValidateReturnValueV2(response.JsonString, "fs_P58E4210_W58E4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NWno = $"NR{obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_757"]["value"].ToString()}";
                    NWno += $"#{ obj["fs_P58E4210_W58E4210A"]["data"]["z_DCTO_774"]["value"].ToString()}{ obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_776"]["value"].ToString()}";
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NR单:{NWno}");
                    Log4Net.Error($"按申请数量 新增NR单据 {param.orderid} 生成NR单:{NWno}");
                    execresult.Result = NWno;
                    execresult.Message = response.JsonString;
                }
            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message.Substring(0, 20)}");

                execresult.ResponseCode = CommonHandler.GetExceptionV2(x.Message, "CODE", new List<string>() { "500" })[0].ToString();

                execresult.Message = string.Join(Environment.NewLine,
                                                CommonHandler.GetExceptionV2(x.Message, "DESC", new List<string>() { x.Message }, detailinfos)
                                                );
                Console.WriteLine($"{DateTime.Now.ToString()}  请求返回异常:{execresult.Message}");
            }
            return execresult;


        }


        [HttpPost]
        public ActionResult<MQResponse> CreateReturnNR(dynamic objparam)
        {
            Console.WriteLine(objparam);
            Dictionary<int, string> detailinfos = new Dictionary<int, string>();
            int index = 0;
            //用了新的方式，哈哈方便多了
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()} 新增退厂NR单据 {param.orderid}");
                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();

                foreach (DataRow dr in new BLL.orderHandler().GetReturnNROrder(param.orderid)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString().Trim(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "53", value = (Convert.ToInt32( dr["Quantity"])*-1).ToString()  , command = "SetGridCellValue" });
                    if (Convert.ToInt32(dr["Quantity"].ToString()) != 0)
                    {
                        Console.WriteLine($"{DateTime.Now.ToString()}  {dr["ItemNumber"]},{dr["Quantity"]}  ");
                        gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                        detailinfos.Add(index, SetErrLineMsg(index.ToString(), dr["ItemNumber"].ToString(), dr["Quantity"].ToString(),"" ));
                        index++;
                    }
                    lastrow = dr;
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        new FSREvent() { controlID="716", command="SetControlValue", value= lastrow["FromBU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="718", command="SetControlValue",value=lastrow["ToBU"].ToString()   },
                                        //new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        //new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        //new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P4210_W4210A",
                    version = "MBR001RC",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                //System.Threading.Thread.Sleep(3000);
                if (CommonHandler.ValidateReturnValueV2(response.JsonString, "fs_P4210_W4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NWno = $"NR{obj["fs_P4210_W4210A"]["data"]["z_DOCO_757"]["value"].ToString()}";
                    NWno += $"#{ obj["fs_P4210_W4210A"]["data"]["z_DCTO_774"]["value"].ToString()}{ obj["fs_P4210_W4210A"]["data"]["z_DOCO_776"]["value"].ToString()}";
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成负数NR单:{NWno}");
                    execresult.Result = NWno;
                    execresult.Message = response.JsonString;
                }
            }
            catch (Exception x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message.Substring(0, 20)}");

                execresult.ResponseCode = CommonHandler.GetExceptionV2(x.Message, "CODE", new List<string>() { "500" })[0].ToString();

                execresult.Message = string.Join(Environment.NewLine,
                                                CommonHandler.GetExceptionV2(x.Message, "DESC", new List<string>() { x.Message }, detailinfos)
                                                );
                Console.WriteLine($"{DateTime.Now.ToString()}  请求返回异常:{execresult.Message}");
            }
            return execresult;


        }

        [HttpPost]
        ///扣减公共份额后，进行采购
        public ActionResult<MQResponse> CreateNRSubsharequantity(dynamic objparam)
        {
            Console.WriteLine(objparam);
            Dictionary<int, string> detailinfos = new Dictionary<int, string>();
            int index = 0;
            //用了新的方式，哈哈方便多了
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objparam).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new MQException("120","请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("406", "当前单据无数据");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()}  排除公共份额数量后 新增NR单据 {param.orderid}");
                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();
                DataTable DT = new BLL.orderHandler().GetNROrder(param.orderid)[0];

                if (DT.Rows.Count <= 0)
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }
                foreach (DataRow dr in DT.Rows)
                {
                    if (Convert.ToInt32(dr["purchasequantity"].ToString()) != 0)
                    {
                        gridcolumnCollection col = new gridcolumnCollection();
                        col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "1065", value = dr["fromInvregion"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "608", value = dr["ToInvregion"].ToString(), command = "SetGridCellValue" });
                        col.Add(new gridcolumnevent() { columnID = "53", value = dr["purchasequantity"].ToString(), command = "SetGridCellValue" });
                        //col.Add(new gridcolumnevent() { columnID = "132", value = dr["location"].ToString(), command = "SetGridCellValue" });
                        //col.Add(new gridcolumnevent() { columnID = "133", value = dr["lotn"].ToString(), command = "SetGridCellValue" });
                        //col.Add(new gridcolumnevent() { columnID = "663", value = dr["LOB"].ToString(), command = "SetGridCellValue" });

                        //if ("/PRI/SRI/".IndexOf("/" + dr["Tolocation"].ToString().ToUpper() + "/") < 0)
                        //{
                        //    col.Add(new gridcolumnevent() { columnID = "456", value = dr["Tolocation"].ToString(), command = "SetGridCellValue" });
                        //}
                        if (!string.IsNullOrWhiteSpace(dr["ShipToCode"].ToString()))
                        {
                            col.Add(new gridcolumnevent() { columnID = "164", value = dr["ShipToCode"].ToString(), command = "SetGridCellValue" });
                        }
                        //2024-06-27 IT 要求增加配额到664  最终用途中
                        if (!string.IsNullOrWhiteSpace(dr["ToQuota"].ToString()))
                        {
                            col.Add(new gridcolumnevent() { columnID = "664", value = dr["ToQuota"].ToString(), command = "SetGridCellValue" });
                        }

                        if (Convert.ToInt32(dr["purchasequantity"].ToString()) != 0)
                        {
                            Console.WriteLine($"{DateTime.Now.ToString()}  {dr["ItemNumber"]},{dr["purchasequantity"]}, {dr["fromInvregion"]}");
                            gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                            detailinfos.Add(index, SetErrLineMsg(index.ToString(), dr["ItemNumber"].ToString(), dr["purchasequantity"].ToString(), dr["fromInvregion"].ToString()));
                            index++;
                        }
                        lastrow = dr;
                    }
                }
                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        new FSREvent() { controlID="716", command="SetControlValue", value= lastrow["FromBU"].ToString() },
                                        //new FSREvent() { controlID="23", command="SetControlValue",value=DateTime.Now.ToString("yyyy/MM/dd", System.Globalization.DateTimeFormatInfo.InvariantInfo)},
                                        new FSREvent() { controlID="718", command="SetControlValue",value=lastrow["ToBU"].ToString()   },
                                        //new FSREvent() { controlID="802", command="SetControlValue",value= lastrow["shipaddress"].ToString() },
                                        //new FSREvent() { controlID="697", command="SetControlValue",value= lastrow["OrderNumber"].ToString() },
                                        //new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P58E4210_W58E4210A",
                    version = "MBR001",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                //System.Threading.Thread.Sleep(3000);
                Log4Net.Error($"CreateNRSubsharequantity:{response.JsonString}");
                if (CommonHandler.ValidateReturnValueV2(response.JsonString, "fs_P58E4210_W58E4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NWno = $"NR{obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_757"]["value"].ToString()}";
                    NWno += $"#{ obj["fs_P58E4210_W58E4210A"]["data"]["z_DCTO_774"]["value"].ToString()}{ obj["fs_P58E4210_W58E4210A"]["data"]["z_DOCO_776"]["value"].ToString()}";
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NR单:{NWno}");
                    execresult.Result = NWno;
                    execresult.Message = response.JsonString;
                }
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message.Substring(0, 20)}");

                execresult.ResponseCode = CommonHandler.GetExceptionV2(x.Message, "CODE", new List<string>() { "500" })[0].ToString();

                execresult.Message = string.Join(Environment.NewLine,
                                                CommonHandler.GetExceptionV2(x.Message, "DESC", new List<string>() { x.Message }, detailinfos)
                                                );
                Console.WriteLine($"{DateTime.Now.ToString()}  请求返回异常:{execresult.Message}");

                //execresult.Result = x.Message.Replace("\\u000a",Environment.NewLine);
            }
            return execresult;


        }

        /// <summary>
        ///  修改销售单表头为XQ33
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> UpdateMasterTable(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            //用了新的方式，哈哈方便多了
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objpram).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;
            try
            {

                if (param.ordernumber.Length > 8)
                {
                    throw new MQException("120", $"修改订单表头时，请求的单号长度过长！   {param.ordernumber}");
                }
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new MQException("401","请求的用户名或密码为空！");
                }
 
                token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");

                Console.WriteLine($"{DateTime.Now.ToString()} 查找NA单据 {param.ordernumber}");

                
                #region 处理代码
                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    returnControlIDs = "1[45,46,47]",
                    formName = "P4210_W4210E",
                    version = "MBR003A",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                   ,
                    formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                      new FSREvent() { controlID="1[45]", command="SetQBEValue" ,value=param.ordernumber },
                                      new FSREvent() { controlID="28", command="DoAction"  }
                                     }
                                 )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P4210_W4210E",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };

                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210E"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt16(obj["fs_P4210_W4210E"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"{ DateTime.Now.ToString()} 查询到{ rowcount - 1}条记录");


                    if (rowcount > 1)
                    {
                        Console.WriteLine($"{ DateTime.Now.ToString()} 选择第一条记录，并打开编辑界面");
                        ActionRequest actionRequest = new ActionRequest()
                        {
                            //returnControlIDs = "1[53,89,35,132,133,34,664]",
                            formOID = "W4210E",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                      new FSREvent() { controlID="1.0", command="SelectRow"   },
                                      new FSREvent() { controlID="252", command="DoAction"  }
                                      }
                                  )
                             ,
                            stopOnWarning = "false"
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        needclose = true;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210G"))
                        {
                            ///获取结果的总行数
                            obj = response.ToJObject();
                            actionRequest = new ActionRequest()
                            {
                                //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W4210G",
                                formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {
                                              new FSREvent() { controlID="90", command="SetControlValue"  ,value=param.INMG },
                                              new FSREvent() { controlID="3", command="DoAction"  }
                                         }
                                     )
                                 ,
                                stopOnWarning = "false"
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                //allowCache = true,
                                action = "execute",
                                
                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };
                            Console.WriteLine( $"{ DateTime.Now.ToString()} 录入表头{param.INMG}并保存");
                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            needclose = true;
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                            //Console.WriteLine(response.JsonString);
                            // 
                             
                           if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210A"))
                                {
                                    
                                    obj = response.ToJObject();
                                    actionRequest = new ActionRequest()
                                    {
                                        //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                        formOID = "W4210A",
                                        formActions = new FormActionsCollection
                                        (
                                            new FSREvent[]
                                            {
                                                new FSREvent() { controlID="4", command="DoAction"  }
                                            }
                                        )
                                    ,
                                        stopOnWarning = "false"
                                    };
                                    asrequest = new ApplicationStackRequest()
                                    {
                                        outputType = "VERSION2",
                                        allowCache = true,
                                        action = "execute",
                                        actionRequest = actionRequest,
                                        stackId = response.stackId,//上一次返回的值
                                        stateId = response.stateId,
                                        rid = response.rid
                                    };
                                    Console.WriteLine($"{DateTime.Now.ToString()} {param.ordernumber}  明细行确认 ");
                                    response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                                    needclose = true;
                                    stackId = response.stackId;
                                    stateId = response.stateId;
                                    rid = response.rid;
                                     if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210E"))
                                    {
                                        Console.WriteLine($"{DateTime.Now.ToString()} {param.ordernumber}修改完成:{response.currentApp}");
                                        execresult.Result = param.ordernumber;
                                        execresult.Message = response.JsonString;

                                    }

                                    
                                }



                        }

                    }
                    else
                    {
                        throw new MQException("404", $"找不到单据{param.ordernumber},请联系管理员！");
                    }
                }
                #endregion
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W4210E"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    //Console.WriteLine(response.JsonString);
                }
                #endregion
            }
            return execresult;
        }


        /// <summary>
        /// 修改送货地址，用于其他区域调拨CD时，系统默认是广州的地址
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> UpdateShipto(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            //用了新的方式，哈哈方便多了
            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objpram).ToString());
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            int stackId = 0;
            int stateId = 0;
            string rid = "";
            string token = "";
            bool needclose = false;
            try
            {

                #region 权限验证
                if (param.ordernumber.Length > 8)
                {
                    throw new Exception($"修改订单表头时，请求的单号长度过长！   {param.ordernumber}");
                }
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }

                token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                #endregion

                Console.WriteLine($"{DateTime.Now.ToString()} 查找NW单据 {param.ordernumber}");


                #region 处理代码
                FormRequest formRequest = new FormRequest()
                {
                    //maxPageSize = "2",
                    returnControlIDs = "1[45,46,47]",
                    formName = "P4210_W4210E",
                    version = "MBR001WD",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true
                   ,
                    formActions = new FormActionsCollection
                                 (
                                     new FSREvent[]
                                     {
                                      new FSREvent() { controlID="1[45]", command="SetQBEValue" ,value=param.ordernumber },
                                      new FSREvent() { controlID="28", command="DoAction"  }
                                     }
                                 )
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    action = "open",
                    outputType = "VERSION2",
                    formName = "P4210_W4210E",
                    stackId = stackId,
                    stateId = stateId,
                    formRequest = formRequest

                };
                //1、查单据
                AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                //Console.WriteLine(response.JsonString);
                stackId = response.stackId;
                stateId = response.stateId;
                rid = response.rid;
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210E"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt16(obj["fs_P4210_W4210E"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"{ DateTime.Now.ToString()} 查询到{ rowcount - 1}条记录");


                    if (rowcount > 1)
                    {
                        Console.WriteLine($"{ DateTime.Now.ToString()} 选择第一条记录，并打开编辑界面");
                        ActionRequest actionRequest = new ActionRequest()
                        {
                            //returnControlIDs = "1[53,89,35,132,133,34,664]",
                            formOID = "W4210E",
                            formActions = new FormActionsCollection
                                  (
                                      new FSREvent[]
                                      {
                                      new FSREvent() { controlID="1.0", command="SelectRow"   },
                                      new FSREvent() { controlID="252", command="DoAction"  }
                                      }
                                  )
                             ,
                            stopOnWarning = "false"
                        };

                        asrequest = new ApplicationStackRequest()
                        {
                            outputType = "VERSION2",
                            allowCache = true,
                            action = "execute",
                            actionRequest = actionRequest,
                            stackId = stackId,
                            stateId = stateId,
                            rid = response.rid
                        };
                        //2 、打开表头编辑界面
                        response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                        stackId = response.stackId;
                        stateId = response.stateId;
                        rid = response.rid;
                        needclose = true;
                        if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210G"))
                        {
                            ///获取结果的总行数
                            obj = response.ToJObject();
                            actionRequest = new ActionRequest()
                            {
                                //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                formOID = "W4210G",
                                formActions = new FormActionsCollection
                                     (
                                         new FSREvent[]
                                         {
                                              new FSREvent() { controlID="460", command="SetControlValue"  ,value=param.shiptocode },
                                              new FSREvent() { controlID="3", command="DoAction"  }
                                         }
                                     )
                                 ,
                                stopOnWarning = "false"
                            };
                            asrequest = new ApplicationStackRequest()
                            {
                                outputType = "VERSION2",
                                //allowCache = true,
                                action = "execute",

                                actionRequest = actionRequest,
                                stackId = response.stackId,//上一次返回的值
                                stateId = response.stateId,
                                rid = response.rid
                            };
                            Console.WriteLine($"{ DateTime.Now.ToString()} 录入表头{param.shiptocode}并保存");
                            //3、保存
                            response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                            needclose = true;
                            stackId = response.stackId;
                            stateId = response.stateId;
                            rid = response.rid;
                            //Console.WriteLine(response.JsonString);
                            // 

                            if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210A"))
                            {

                                obj = response.ToJObject();
                                actionRequest = new ActionRequest()
                                {
                                    //returnControlIDs = "1[348,440,257,45,46,47,48,49,50,51]",
                                    formOID = "W4210A",
                                    formActions = new FormActionsCollection
                                    (
                                        new FSREvent[]
                                        {
                                                new FSREvent() { controlID="4", command="DoAction"  }
                                        }
                                    )
                                ,
                                    stopOnWarning = "false"
                                };
                                asrequest = new ApplicationStackRequest()
                                {
                                    outputType = "VERSION2",
                                    allowCache = true,
                                    action = "execute",
                                    actionRequest = actionRequest,
                                    stackId = response.stackId,//上一次返回的值
                                    stateId = response.stateId,
                                    rid = response.rid
                                };
                                Console.WriteLine($"{DateTime.Now.ToString()} {param.ordernumber}  明细行确认 ");
                                response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                                needclose = true;
                                stackId = response.stackId;
                                stateId = response.stateId;
                                rid = response.rid;
                                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210E"))
                                {
                                    Console.WriteLine($"{DateTime.Now.ToString()} {param.ordernumber}修改完成:{response.currentApp}");
                                    execresult.Result = param.ordernumber;
                                    execresult.Message = response.JsonString;

                                }


                            }



                        }

                    }
                    else
                    {
                        throw new MQException("404", $"找不到单据{param.ordernumber},请联系管理员！");
                    }
                }
                #endregion
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            finally
            {
                #region Close

                ActionRequest actionRequest = new ActionRequest()
                {
                    //returnControlIDs = "1[17,18,19,20]",
                    formOID = "W4210E"
                };
                ApplicationStackRequest asrequest = new ApplicationStackRequest()
                {
                    outputType = "VERSION2",
                    allowCache = true,
                    action = "close",
                    actionRequest = actionRequest,
                    stackId = stackId,//上一次返回的值
                    stateId = stateId,
                    rid = rid
                };
                if (!string.IsNullOrWhiteSpace(token) && needclose)
                {
                    AppstackResponse response = AISClientHandler.Instance.Appstack_execute(token, asrequest);
                    //Console.WriteLine(response.JsonString);
                }
                #endregion
            }
            return execresult;
        }


        /// <summary>
        /// 创建NV单
        /// </summary>
        /// <param name="objpram"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<MQResponse> CreateNV(dynamic objpram)
        {
            Log4Net.Debug(objpram);
            Dictionary<int, string> detailinfos = new Dictionary<int, string>();
            int index = 0;
            //string username = objpram["username"].ToString();
            //string password = objpram["password"].ToString();
            //string ordernumber = objpram["ordernumber"].ToString();

            P4210param param = Common.JsonHelper.JsonToObject<P4210param>((objpram).ToString());


            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {

                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new Exception("请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);

                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"username:{param.username} Token:{token}");
                Console.WriteLine($"{DateTime.Now.ToString()} 新增NV单据 {param.orderid}  ");

                List<gridrowInsertevents> gridrows = new List<gridrowInsertevents>();
                FormActionsCollection fs = new FormActionsCollection();
                DataRow lastrow = new DataTable().NewRow();


                foreach (DataRow dr in new BLL.orderHandler().GetNVOrder(param.orderid)[0].Rows)
                {
                    gridcolumnCollection col = new gridcolumnCollection();
                    col.Add(new gridcolumnevent() { columnID = "89", value = dr["ItemNumber"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "57", value = dr["actualamount"].ToString(), command = "SetGridCellValue" });
                    col.Add(new gridcolumnevent() { columnID = "608", value = dr["sourceordernumber"].ToString(), command = "SetGridCellValue" });


                    gridrows.Add(new gridrowInsertevents() { gridColumnEvents = col });
                    // detailinfos.Add(index, SetErrLineMsg(index.ToString(), dr["ItemNumber"].ToString(), dr["actualamount"].ToString() ));
                    index++;
                    lastrow = dr;
                }


                if (lastrow.Table.Rows.Count <= 0)
                    throw new MQException("401", $"订单{param.ordernumber} 没有可以生成的数据！");


                fs.AddRange(
                     new FormActionsCollection
                              (
                                  new FSREvent[]
                                  {
                                        new FSREvent() { controlID="800", command="SetControlValue",value=lastrow["clientcode"].ToString()   },
                                        new FSREvent() { controlID="519", command="SetCheckboxValue",value= "off" }
                                  }
                              )
                    );
                GridAction gridAction = new GridAction();
                gridAction.gridID = "1";
                gridAction.gridRowInsertEvents = gridrows;

                fs.Add(new FSREvent() { command = "SelectRow", gridAction = gridAction });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "4" });

                FormRequest request = new FormRequest()
                {
                    formName = "P4210_W4210A",
                    version = "MBR001VN",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "20",
                    formServiceAction = "C",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                System.Threading.Thread.Sleep(1000);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4210_W4210A"))
                {
                    JObject obj = response.ToJObject();
                    //应该查询到数据
                    string NAno = obj["fs_P4210_W4210A"]["data"]["z_DOCO_28"]["value"].ToString();
                    Console.WriteLine($"{DateTime.Now.ToString()} 生成NV单:{NAno}");
                    Log4Net.Debug($"{param.orderid}生成NV单:{NAno}");
                    execresult.Result = NAno;
                }

            }
            catch (Exception x)
            {
                Log4Net.Error($"{param.ordernumber}请求异常:{x.Message}");
                Console.WriteLine($"{DateTime.Now.ToString()}  请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", "500").ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
                if (string.IsNullOrWhiteSpace(execresult.Message))
                {
                    execresult.Message = CommonHandler.GetException(x.Message, "TITLE", x.Message).ToString();
                }
                //2023-10-16 增加当可供量不足的时候，提示是哪一行
                int errline = CommonHandler.GetErrorControlLine(x.Message);
                if (errline >= 0)
                    execresult.Message += System.Environment.NewLine + detailinfos[errline];

                Console.WriteLine($"{DateTime.Now.ToString()}  请求返回异常:{execresult.Message}");
                execresult.Result = x.Message;
            }
            return execresult;
        }
        private string SetErrLineMsg(string linenum, string itemnumber, string qty, string invergion)
        {
            string msg = $"第{Convert.ToInt32( linenum)+1}行中的{itemnumber}本次请求数量{qty},在份额:[{invergion}]不能满足，请检查！";
            return msg;
        }
    }
}